<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/9/25
 * Time: 14:16
 */

namespace app\home\controller;

use app\home\logic\OrderLogic;
use think\Controller;
use think\Db;
use think\Session;

class Payment extends Controller {

    public $payment; //  具体的支付类
    public $pay_code; //  具体的支付code
    private $user = false;
    public $config = false;

    public function _initialize(){
        Session::start();
        parent::_initialize();
        $this->user = $this->user();
        $this->config = $this->config();
        include_once  "plugins/payment/weixin/weixin.class.php";
        $code = '\\weixin';
        $this->payment = new $code();
    }

    //配置文件
    public function config(){
        $config = array();
        $m_config = M('config')->cache(true,MT_CACHE_TIME)->select();
        foreach($m_config as $k => $v){
            if($v['name'] == 'hot_keywords'){
                $config['hot_keywords'] = explode('|', $v['value']);
            }
            $config[$v['inc_type'].'_'.$v['name']] = $v['value'];
        }
        $this->assign('config', $config);
    }

    public function user(){
        $where['openid'] = session('openid');
        if(!empty(trim($where['openid']))){
            $user = M('user')->where($where)->find();
            unset($user['verification']);
            unset($user['password']);
            return $user;
        }
        return false;
    }


    //预订球位-预支付订单
    public function pay_order(){
        if (!$this->user) $this->redirect('User/login');
        if (IS_AJAX){
            $data = trim_array_element(I('param.'));
            $pay_order = M('order')->where(array('order_sn' => $data['itemid']))->find();
            if ($pay_order['order_status'] != 0) ajaxReturn(array('status' => 500,'msg' => '订单状态错误，请前往订单列表查看','url' => U('Order/index')));
            if ($data['is_use'] == 1){ //使用余额+微信支付
                $balance = $this->user['balance'];
                if ($balance >= $pay_order['goods_price']){ //直接余额支付成功
                    Db::startTrans();
                    try{
                        //标识订单已经支付
                        Db::name('order')->where(array('order_sn' => $pay_order['order_sn']))->save(array(
                            'order_status' => 1, //已支付
                            'pay_time' => time(),
                            'pay_code' => '余额支付',
                        ));
                        //扣除余额
                        Db::name('user')->where(array('user_id' => $this->user['user_id']))->setDec('balance',$pay_order['goods_price']);
                        //增加消费记录
                        Db::name('expense')->insert(array(
                            'user_id' => $this->user['user_id'],
                            'type' => 1,
                            'add_time' => time(),
                            'amount' => $pay_order['goods_price'],
                            'remark' => '余额消费'
                        ));
                        Db::commit();
                        //发送短信
                        $result = (new \app\common\logic\SmsLogic)->notice(
                            $pay_order['phone'],
                            date('Y年m月d日',$pay_order['subscribe_time']),
                            mb_substr($pay_order['goods_name'],2,1,'utf-8'),
                            date('H:i',$pay_order['subscribe_time'])
                        );

                        ajaxReturn(array('status' => 400,'msg' => '预约订单-余额支付成功','url' => U('Order/index')));
                    }catch (\Exception $e){
                        Db::rollback();
                        ajaxReturn(array('status' => 500,'msg' => '系统出错，请联系管理员'));
                    }
                }elseif ($balance == 0){ //并没有余额
                    $pay_order['type'] = 1; //标识这是预约订单支付
                    $pay_order['openid'] = $this->user['openid'];
                    $pay_order['is_use'] = 0; //
                    $code_str = $this->payment->getJSAPI($pay_order);
                    ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
                }else{ //微信支付补齐差价
                    $pay_order['goods_price'] = round($pay_order['goods_price'] - $balance,2);
                    $pay_order['type'] = 1; //标识这是预约订单支付
                    $pay_order['openid'] = $this->user['openid'];
                    $pay_order['is_use'] = 1; //是否使用余额
                    $code_str = $this->payment->getJSAPI($pay_order);
                    ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
                }
            }else{ //直接使用微信支付
                $pay_order['type'] = 1; //标识这是预约订单支付
                $pay_order['openid'] = $this->user['openid'];
                $pay_order['is_use'] = 0; //
                if ($pay_order['phone'] == '13880449239') $pay_order['goods_price'] = 0.01;
                $code_str = $this->payment->getJSAPI($pay_order);
                ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
            }
        }
        $order_id = I('param.itemid');
        $order = M('order')->where(array('order_sn' => $order_id))->find();
        $this->assign('order',$order);
        $this->assign('user',$this->user);
        $this->assign('title','支付订单');
        return $this->fetch();
    }

    //充值订单
    public function pay_recharge_order(){
        if (!$this->user) $this->redirect('User/login');
        $recharge_id = I('param.itemid');
        $order = M('recharge')->where(array('recharge_id' => $recharge_id))->find();
        if ($order['status'] != 0) ajaxReturn(array('status' => 500,'msg' => '充值订单状态错误，请退出重试'));

        $order['order_sn'] = date('YmdHi').rand(100000,9999999);
        $order['goods_price'] = $order['amount'];
        $order['openid'] = $this->user['openid'];
        $order['order_id'] = $order['recharge_id'];
        $order['type'] = 2; //标识未充值订单
        $order['is_use'] = 0;
        $code_str = $this->payment->getJSAPI($order);
        ajaxReturn(array('status' => 200,'msg' => '订单支付中..','result' => json_decode($code_str,true)));
    }

    //商场订单-结算页面-购物车结算
    public function settlement(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        if (IS_AJAX){
            $data = trim_array_element(I('param.'));
            if ($data['address_id'] == '') ajaxReturn(array('status' => 500,'msg' => '500：地址参数为空'));
            $address = M('user_address')->where(array('address_id' => $data['address_id']))->find();
            //获取订单中的商品
            $order_goods = M('cart')->where(['user_id'=> $this->user['user_id'],'selected'=>1])->select();
            $result = calculate_price($order_goods);
            if($result['status'] < 0)
                ajaxReturn(array('status' => 500,'msg' => $result['msg']));
            $orderLogic = new OrderLogic();
            $result = $orderLogic->addOrder($this->user['user_id'],$result['result'],$address,$data['distribution_way'],$data['user_note']); // 添加订单
            if ($result['status'] == 200){
                $order = M('shop_order')->where(array('order_id' => $result['result']))->find();
                if ($data['pay_way'] == 1){ //微信支付
                    $order['type'] = 3; //标识商场订单
                    $order['is_use'] = 0; //不使用积分
                    $order['openid'] = $this->user['openid'];
                    $code_str = $this->payment->getJSAPI($order);
                    ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
                }elseif ($data['pay_way'] == 2){ //积分支付
                    $integral = $this->user['integral']; //所拥有的积分
                    $goods_price = $order['goods_price'] * 10; //需要支付的积分
                    if ($integral >= $goods_price){ //足够支付
                        Db::startTrans();
                        try{
                            //扣除积分
                            M('user')->where(array('user_id' => $this->user['user_id']))->setDec('integral',$goods_price);
                            //改变订单状态
                            M('order')->where(array('order_id' => $order['order_id']))->save(array(
                                'order_status' => 1, //订单状态，待发货
                                'pay_time' => time(), //支付时间
                                'pay_code' => '积分支付', //支付方式
                            ));
                            ajaxReturn(array('status' => 400,'msg' => '积分支付成功！','url' => U('Order/shop_detail',array('item_id' => $order['order_id']))));
                        }catch (\Exception $e){
                            Db::rollback();
                            ajaxReturn(array('status' => 500,'msg' => '系统出错，请联系管理员'));
                        }
                    }else{
                        ajaxReturn(array('status' => 500,'msg' => '剩余积分不足！','url' => U('Order/shop_detail',array('item_id' => $order['order_id']))));
                    }
                }elseif ($data['pay_way'] == 3){ //微信+积分支付
                    //拥有的积分
                    $integral = $this->user['integral']; //所拥有的积分
                    $goods_price = $order['goods_price'] * 10; //需要支付的积分
                    if ($integral < $goods_price){ //调用微信支付
                        $amount = round(($goods_price - $integral) / 10,2);
                        $order['goods_price'] = $amount;
                        $order['type'] = 3; //标识商场订单
                        $order['is_use'] = 1; //不使用积分
                        $order['openid'] = $this->user['openid'];
                        $code_str = $this->payment->getJSAPI($order);
                        ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
                    }else{
                        ajaxReturn(array('status' => 500,'msg' => '积分足够，请直接选择使用积分支付','url' => U('Order/shop_detail',array('item_id' => $order['order_id']))));
                    }
                }
            }else{
                ajaxReturn(array('status' => 500,'msg' => $result['msg']));
            }
        }
        //获取默认地址
        $address = M('user_address')->where(array('user_id' => $this->user['user_id'],'is_default' => 1))->find();
        $this->assign('address',$address);
        $orderLogic = new OrderLogic();
        $result = $orderLogic->getCartList($this->user['user_id'],1,1);
        if(empty($result['total_price'])){
            $this->error('请先选择结算的商品');
        }
        foreach ($result['cartList'] as $k=>$v){
            $result['cartList'][$k]['original_img'] = M('goods')->where(['goods_id' => $result['cartList'][$k]['goods_id']])->getField('original_img');
        }
        $this->assign('cartList', $result['cartList']);
        $this->assign('total_price', $result['total_price']); // 总计
        $this->assign('title','确认订单');
        return $this->fetch();
    }


    //商场订单-结算页面-购物车结算
    public function confirm(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        if (IS_AJAX){
            if (!$this->user) ajaxReturn(array('status' => 500,'url' => U('User/login',array('type' => 2))));
            $data = trim_array_element(I('param.'));
            session('goods_id',$data['goods_id']);
            session('goods_spec',$data['goods_spec']);
            session('goods_num',$data['goods_num']);
            ajaxReturn(array('status' => 200,'url' => '/home/payment/confirm.html'));
        }
        //获取默认地址
        $address = M('user_address')->where(array('user_id' => $this->user['user_id'],'is_default' => 1))->find();
        $this->assign('address',$address);

        //商品信息
        $goods = M('goods')->where(array('goods_id' => session('goods_id')))->find();
        $this->assign('goods',$goods);

        //商品规格信息
        $spec_goods_price = M('spec_goods_price')->where(array('goods_id' => $goods['goods_id'],'key' => session('goods_spec')))->find();
        $this->assign('spec_goods_price',$spec_goods_price);
        //商品数量
        $this->assign('goods_num',session('goods_num'));
        $this->assign('title','确认订单');
        $this->assign('user',$this->user);
        return $this->fetch();
    }

    public function confirm_add_order(){
        if (!$this->user) $this->redirect('User/login',array('type' => 2));
        session('goods_id',null);
        session('goods_spec',null);
        session('goods_num',null);
        if (IS_AJAX){
            if (!$this->user) ajaxReturn(array('status' => 500,'url' => U('User/login',array('type' => 2))));
            $data = trim_array_element(I('param.'));
            if ($data['goods_spec'] == '')  ajaxReturn(array('status' => 500,'msg' => '请选规格'));
            //获取地址参数
            if ($data['address_id'] == '') ajaxReturn(array('status' => 500,'msg' => '500：地址参数为空'));
            $address = M('user_address')->where(array('address_id' => $data['address_id']))->find();
            //获取该商品相关参数
            if ($data['goods_id'] == '' || $data['goods_num'] == '') ajaxReturn(array('status' => 500,'msg' => '500：商品参数错误'));
            $goods = M('goods')->where(array('goods_id' => $data['goods_id']))->find(); //商品参数
            $goods['spec_goods_price'] = M('spec_goods_price')->where(array('goods_id' => $goods['goods_id'],'key' => $data['goods_spec']))->find(); //商品规格参数
            $goods['goods_num'] = $data['goods_num'];
            //判断库存是否足够
            if ($goods['spec_goods_price']['store_count'] != ''){
                if ($data['goods_num'] > $goods['spec_goods_price']['store_count']) ajaxReturn(array('status' => 500,'msg' => '500：商品库存不足'));
            }else{
                if ($data['goods_num'] > $goods['store_count']) ajaxReturn(array('status' => 500,'msg' => '500：商品库存不足'));
            }
            $orderLogic = new OrderLogic();
            $result = $orderLogic->addOrder2($this->user['user_id'],$goods,$address,$data['distribution_way'],$data['user_note']); // 添加订单
            if ($result['status'] == 200){
                $order = M('shop_order')->where(array('order_id' => $result['result']))->find();
                if ($data['pay_way'] == 1){ //微信支付
                    $order['type'] = 3; //标识商场订单
                    $order['is_use'] = 0; //不使用积分
                    $order['openid'] = $this->user['openid'];
                    $code_str = $this->payment->getJSAPI($order);
                    ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
                }elseif ($data['pay_way'] == 2){ //积分支付
                    $integral = $this->user['integral']; //所拥有的积分
                    $goods_price = $order['goods_price'] * 10; //需要支付的积分
                    if ($integral >= $goods_price){ //足够支付
                        Db::startTrans();
                        try{
                            //扣除积分
                            M('user')->where(array('user_id' => $this->user['user_id']))->setDec('integral',$goods_price);
                            //改变订单状态
                            M('order')->where(array('order_id' => $order['order_id']))->save(array(
                                'order_status' => 1, //订单状态，待发货
                                'pay_time' => time(), //支付时间
                                'pay_code' => '积分支付', //支付方式
                            ));
                            ajaxReturn(array('status' => 400,'msg' => '积分支付成功！','url' => U('Order/shop_detail',array('item_id' => $order['order_id']))));
                        }catch (\Exception $e){
                            Db::rollback();
                            ajaxReturn(array('status' => 500,'msg' => '系统出错，请联系管理员'));
                        }
                    }else{
                        ajaxReturn(array('status' => 500,'msg' => '剩余积分不足！','url' => U('Order/shop_detail',array('item_id' => $order['order_id']))));
                    }
                }elseif ($data['pay_way'] == 3){ //微信+积分支付
                    //拥有的积分
                    $integral = $this->user['integral']; //所拥有的积分
                    $goods_price = $order['goods_price'] * 10; //需要支付的积分
                    if ($integral < $goods_price){ //调用微信支付
                        $amount = round(($goods_price - $integral) / 10,2);
                        $order['goods_price'] = $amount;
                        $order['type'] = 3; //标识商场订单
                        $order['is_use'] = 1; //不使用积分
                        $order['openid'] = $this->user['openid'];
                        $code_str = $this->payment->getJSAPI($order);
                        ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
                    }else{
                        ajaxReturn(array('status' => 500,'msg' => '积分足够，请直接选择使用积分支付','url' => U('Order/shop_detail',array('item_id' => $order['order_id']))));
                    }
                }
            }else{
                ajaxReturn(array('status' => 500,'msg' => $result['msg']));
            }
        }
    }

    //商场订单支付
    public function shop_pay_order(){
        if (!$this->user) ajaxReturn(array('status' => 500,'url' => U('User/login',array('type' => 2))));
        if (IS_AJAX){
            $item_id = I('param.item_id');
            $order = M('shop_order')->where(array('order_id' => $item_id))->find();
            if ($order['order_status'] != 0) ajaxReturn(array('status' => 500,'msg' => '订单状态错误'));
            $order['type'] = 3; //标识商场订单
            $order['is_use'] = 0; //不使用积分
            $order['openid'] = $this->user['openid'];
            //dump($order);die;
            $code_str = $this->payment->getJSAPI($order);
            ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
        }
    }

    //订餐购物车结算
    public function meal_order(){
        if (!$this->user) $this->redirect('User/login',array('type' => 3));
        if (IS_AJAX){
            $data = trim_array_element(I('param.'));
            //获取订单中的商品
            $order_goods = M('meal_cart')->where(['user_id'=> $this->user['user_id'],'selected'=>1])->select();
            $result = calculate_price($order_goods);
            if($result['status'] < 0)
                ajaxReturn(array('status' => 500,'msg' => $result['msg']));
            $orderLogic = new OrderLogic();
            $result = $orderLogic->addOrder3($this->user['user_id'],$result['result'],$data['user_note']); // 添加订单
            if ($result['status'] == 200){
                $order = M('meal_order')->where(array('order_id' => $result['result']))->find();
                $order['type'] = 4; //标识订餐订单
                $order['is_use'] = 0; //不使用积分
                $order['openid'] = $this->user['openid'];
                $code_str = $this->payment->getJSAPI($order);
                ajaxReturn(array('status' => 200,'msg' => '订单支付中','result' => json_decode($code_str,true)));
            }else{
                ajaxReturn(array('status' => 500,'msg' => $result['msg']));
            }
        }
        $orderLogic = new OrderLogic();
        $result = $orderLogic->getCartList2($this->user['user_id'],1,1);
        if(empty($result['total_price'])){
            $this->error('请先选择结算的商品');
        }
        foreach ($result['cartList'] as $k=>$v){
            $result['cartList'][$k]['original_img'] = M('goods')->where(['goods_id' => $result['cartList'][$k]['goods_id']])->getField('original_img');
            $result['cartList'][$k]['goods_remark'] = M('goods')->where(['goods_id' => $result['cartList'][$k]['goods_id']])->getField('goods_remark');
        }
        $this->assign('cartList', $result['cartList']);
        $this->assign('total_price', $result['total_price']); // 总计
        $this->assign('title','提交订单');
        return $this->fetch();
    }

    //取消订单
    public function cancel_order(){
        $order_id = I('param.id');
        $order = M('order')->where(array('order_sn' =>$order_id))->find();
        if ($order['order_status'] != 1){
            ajaxReturn(array('status' => 500,'msg' => '订单状态不符合'));
        }
        if ($order['order_status'] == 1){
            $time1 = date('Y-m-d H:i',$order['subscribe_time']); //当前时间
            $last_time = strtotime(date("Y-m-d H:i",strtotime("-2 hour",strtotime($time1))));

            if (time() > $last_time){
                if (time() < $order['subscribe_time']){
                    $order['refund_fee'] = round($order['goods_price'] * 0.8,2);
                    $result = $this->payment->payment_refund($order);
                    if ($result['result_code'] == 'SUCCESS'){
                        M('order')->where(array('order_sn' =>$order['order_sn']))->save(array('order_status' => -1));
                        ajaxReturn(array('status' => 200,'msg' => '取消成功，退款中','url' => U('order/index')));
                    }else{
                        ajaxReturn(array('status' => 500,'msg' => $result['err_code_des']));
                    }
                }else{
                    ajaxReturn(array('status' => 500,'msg' => '已超过预约时间无法取消'));
                }
            }else{
                $order['refund_fee'] = $order['goods_price'];
//                if ($order['phone'] == '13880449239') {
//                    $order['goods_price'] = 0.01;
//                    $order['refund_fee'] = 0.01;
//                }
                $result = $this->payment->payment_refund($order);

                if ($result['result_code'] == 'SUCCESS'){
                    M('order')->where(array('order_sn' =>$order['order_sn']))->save(array('order_status' => -1));
                    ajaxReturn(array('status' => 200,'msg' => '取消成功，退款中','url' => U('order/index')));
                }else{
                    ajaxReturn(array('status' => 500,'msg' => $result['err_code_des']));
                }
            }
        }
    }



    // 服务器点对点 // http://www.tp-shop.cn/index.php/Home/Payment/notifyUrl
    public function notifyUrl(){
        $this->payment->response();
        exit();
    }

    // 页面跳转 // http://www.tp-shop.cn/index.php/Home/Payment/returnUrl
    public function returnUrl(){

    }

    public function notifyBack(){
        $this->payment->transfer_response();
        exit();
    }
}
